# main.py (精简后)
import asyncio
import time
from typing import List
from fastapi import FastAPI, Query, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.websockets import WebSocket,WebSocketDisconnect
from fastapi.responses import StreamingResponse

from services.chat_service import ChatService
from services.connect_mananger import ConnectionManager
from dependencies import get_chat_service,get_websocket_service
from common.request_class import *
from common.response_class import *
from common.database_class import *

app = FastAPI()


# 跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],
)

@app.get("/")
async def read_root():
    return BaseResponse(data={"message": "Hello World"})

@app.websocket("/ai/chat")
async def websocket_endpoint(websocket:WebSocket,client_id=Query(..., alias="clientId"),manager: ConnectionManager = Depends(get_websocket_service), ):
    await manager.connect(websocket, client_id)
    print(f"客户端 [{client_id}] 已连接 WebSocket")
    try:
        while True:
            # 保持连接打开，可以接收客户端心跳或消息
            await websocket.receive_text()
    except WebSocketDisconnect:
        manager.disconnect(client_id)
        print(f"客户端 [{client_id}] 已断开 WebSocket 连接")


@app.post("/ai/chat")
async def chat(request: BaseChat, service: ChatService = Depends(get_chat_service)):
    stream_generator = service.chat_stream(request)
    return StreamingResponse(stream_generator, media_type="text/plain")


@app.post("/ai/chat-and-speech")
async def chat_and_speech_endpoint(request: BaseChat,service:ChatService = Depends(get_chat_service)):
    text_stream_generator = service.stream_chat_and_speech(request)
    return StreamingResponse(text_stream_generator, media_type="text/plain")


@app.get("/ai/getChatList")
async def get_chat_list(service: ChatService = Depends(get_chat_service)):
    data = service.get_chat_list()
    return BaseResponse(data={"message": "查询成功", "data": data})

@app.get("/ai/getChatHistory", response_model=BaseResponse[List[ChatMessage]])
async def get_chat_history(chat_id: str = Query(..., alias="chatId"), service: ChatService = Depends(get_chat_service)):
    result = service.get_chat_history(chat_id)
    return {"message": "查询成功", "data": result}

@app.delete("/ai/deleteChat")
async def delete_chat(chat_id: str = Query(..., alias="chatId"), service: ChatService = Depends(get_chat_service)):
    service.delete_chat(chat_id)
    return BaseResponse(data={"message": "删除成功"})

@app.get("/ai/getCharacterList")
async def get_character_list(service: ChatService = Depends(get_chat_service)):
    data = service.get_character_list()
    return BaseResponse(data={"message": "查询成功", "data": data})

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)